package cn.kbyue.ormdemo.controller;

import cn.kbyue.ormdemo.entity.Person;
import cn.kbyue.ormdemo.service.IPersonService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/person")
@RequiredArgsConstructor
public class PersonController {

    private final IPersonService personService;

    @GetMapping("/list")
    public ResponseEntity<List<Person>> list() {
        return ResponseEntity.ok(personService.list());
    }

    @GetMapping("/page")
    public ResponseEntity<IPage<Person>> page(@RequestParam(required = false, defaultValue = "1") Long current,
                                              @RequestParam(required = false, defaultValue = "10") Long size) {
        return ResponseEntity.ok(personService.page(new Page<>(current, size)));
    }

    @GetMapping("/{id}")
    public ResponseEntity<Person> get(@PathVariable("id") Integer id) {
        return ResponseEntity.ok(personService.getById(id));
    }

    @PostMapping("/query")
    public ResponseEntity<List<Person>> query(@RequestBody Person person) {
        QueryWrapper<Person> wrapper = new QueryWrapper<>();
        wrapper.setEntity(person);
        List<Person> peoples = personService.selectListByWrapper(wrapper);
        return ResponseEntity.ok(peoples);
    }

    @PostMapping("/save")
    public ResponseEntity<Person> save(@RequestBody Person person) {
        boolean saved = personService.save(person);
        if (saved) {
            return ResponseEntity.ok(person);
        }
        return ResponseEntity.badRequest().build();
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<String> delete(@PathVariable Integer id) {
        boolean removed = personService.removeById(id);
        if (removed) {
            return ResponseEntity.ok("删除完成");
        }
        return ResponseEntity.badRequest().body("删除失败");
    }

    @PutMapping("/{id}")
    public ResponseEntity<Person> update(@PathVariable Integer id, @RequestBody Person person) {
        person.setId(id);
        boolean updated = personService.updateById(person);
        if (updated) {
            return ResponseEntity.ok(person);
        }
        return ResponseEntity.badRequest().build();
    }

}
